<?php
namespace app\service;

use app\model\OrderDistributionModel;
use app\model\OrderModel;
use app\model\OrderProfitProcessModel;
use support\facade\Logger;
use EasyWeChat\Factory;
use const support\CORRECT;

class OrderProfitService{

    //订单分账设置分账人操作
    public static function setProfitDivider(int $orderId): bool
    {
        //查询
        $orderProfitProcessData=OrderProfitProcessModel::where([
            'order_id'          =>$orderId,
            'profit_status'     =>0,
            'status'            =>1
        ])->first();
        if (empty($orderProfitProcessData->id)){
            Logger::app('分账设置:无效ID','info',[$orderId]);
            return false;
        }
        $orderProfitProcessData=$orderProfitProcessData->toArray();
        //进行分账人设置操作
        $config=config('wechat.wechat_pay');
        $payment = Factory::payment($config);
        $receiver = [
            "type"          => $orderProfitProcessData['transfer_account_type'],
            "account"       => $orderProfitProcessData['transfer_account'],
            "name"          => $orderProfitProcessData['transfer_account_name'],
            "relation_type" => $orderProfitProcessData['transfer_relation_type'],
        ];
        Logger::app('分账设置:分账人信息','info',$receiver);
        try {
            $result=$payment->profit_sharing->addReceiver($receiver);
            Logger::app('分账设置:添加分账人结果','info',$result);
            if (empty($result['result_code'])){
                Logger::app('分账设置:添加分账人数据异常');
                return false;
            }
            $fail_reason='';
            if ($result['result_code']=='FAIL'){
                $fail_reason=$result['err_code_des'];
                $profit_status=2;
            }else{
                $profit_status=1;
            }
            $ret=OrderProfitProcessModel::where([
                'id'                =>$orderProfitProcessData['id'],
                'profit_status'     =>0,
                'status'            =>1
            ])->update([
                'profit_status'=>$profit_status,
                'fail_reason'  =>$fail_reason,
                'update_time'  =>time()
            ]);
            if (!$ret){
                Logger::app('分账设置:设置分账人更新失败');
                return false;
            }
            return true;
        } catch (\Throwable $e) {
            Logger::app('分账设置:添加分账人失败','info',[$e->getMessage()]);
            return false;
        }
    }

    //确认分账操作
    public static function confirmProfitHandle(int $orderId): bool
    {
        //查询订单分账信息
        $orderProfitProcess=OrderProfitProcessModel::where([
            'order_id'      =>$orderId,
            'profit_status' =>1
        ])->first();
        if (empty($orderProfitProcess->id)){
            Logger::app('确认分账操作:无效订单ID');
            return false;
        }
        $orderProfitProcess=$orderProfitProcess->toArray();
        $config=config('wechat.wechat_pay');
        $payment = Factory::payment($config);
        $res = $payment->profit_sharing->query($orderProfitProcess['transaction_id'],$orderProfitProcess['out_order_no']);
        Logger::app('确认分账操作:查询分账结果','info',[$res]);
        if (empty($res['result_code'])){
            Logger::app('确认分账操作:查询分账结果错误','info',[$res]);
            return false;
        }
        if (isset($res['status']) &&($res['status']=='FINISHED' || $res['status']=='PROCESSING')){
            Logger::app('确认分账操作:该订单已完成分账','info',[$res['status']]);
            return false;
        }
        //获取订单号
        $orderSn=OrderModel::where('id',$orderId)->value('order_sn');
        //进行分账操作
        $sharing = $payment->profit_sharing->share(
            $orderProfitProcess['transaction_id'],
            $orderProfitProcess['out_order_no'],
            [
                "type"          => $orderProfitProcess['transfer_account_type'],
                "account"       => $orderProfitProcess['transfer_account'],
                "amount"        => $orderProfitProcess['profit_amount']*100,
                "description"   => sprintf("分账-订单号：%s",$orderSn)
            ]
        );
        Logger::app('确认分账操作:提交分账请求结果','info',[$sharing]);
        if (empty($sharing['result_code'])){
            Logger::app('确认分账操作:提交分账请求错误','info',[$sharing]);
        }
        //请求有误
        if ($sharing['result_code']!=='SUCCESS'){
            $ret=OrderProfitProcessModel::where([
                'id'      =>$orderProfitProcess['id']
            ])->update([
                'profit_status'=>4,
                'fail_reason'  =>$sharing['err_code_des']??'',
                'update_time'  =>time()
            ]);
            if (!$ret){
                Logger::app('确认分账操作:更新错误信息失败');
                return false;
            }
            return true;
        }
        //更新订单分账进程
        $ret=OrderProfitProcessModel::where([
            'id'      =>$orderProfitProcess['id']
        ])->update([
            'profit_status'=>3,
            'update_time'  =>time()
        ]);
        Logger::app('确认分账操作:更新订单分账进程','info',[$ret]);
        //更新订单表
        $ret=OrderModel::where([
            'id'=>$orderId
        ])->update([
            'is_profit'     =>CORRECT,
            'profit_time'   =>time(),
            'update_time'   =>time()
        ]);
        Logger::app('确认分账操作:更新订单表','info',[$ret]);
        //更新订单分销表
        $ret=OrderDistributionModel::where([
            'order_id'=>$orderId
        ])->update([
            'is_merchant_settlement'     =>CORRECT,
            'merchant_settlement_time'   =>time(),
            'update_time'                =>time()
        ]);
        Logger::app('确认分账操作:更新订单分销表','info',[$ret]);
        return true;
    }


}